import Vue from 'vue'
import Router from 'vue-router'
import Login from "../views/Login";
import store from "../store";
import Home from "../views/Home";
import Teacher from "../components/Teacher";
import EDM from "../components/EDM";
import FOM from "../components/FOM";
import GDM from "../components/GDM";

Vue.use(Router)

const router = new Router({
  routes: [
    {
      path: '/',
      name: 'login',
      component: Login
    },
    {
      path: '/home',
      name: "home",
      component: Home,
      children: [
        {
          path: '/teacher',
          name: 'teacher',
          component: Teacher
        },
        {
          path: '/edm',
          name: 'edm',
          component: EDM
        },
        {
          path: '/fom',
          name: 'fom',
          component: FOM
        },
        {
          path: '/gdm',
          name: 'gdm',
          component: GDM
        }
      ]
    }

  ]
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  // to: Route: 即将要进入的目标 路由对象
  // from: Route: 当前导航正要离开的路由
  // next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
  console.log(store.getters.loginIn)

  const nextRoute = ['home', 'edm', 'fom', 'gdm', 'ojm', 'teacher'];
  let isLogin = store.getters.loginIn;  // 是否登录
  // 未登录状态；当路由到nextRoute指定页时，跳转至login
  if (nextRoute.indexOf(to.name) >= 0) {
    if (!isLogin) {
      router.push({path: '/'})
    }
  }
  // 已登录状态；当路由到login时，跳转至home
  // if (to.name === 'login') {
  //   if (isLogin) {
  //     router.push({ name: 'home' });
  //   }
  // }
  next();
});

export default router
